import os
import re
import sys
import xbmc,xbmcaddon,xbmcgui,xbmcplugin,xbmcgui


from addon.common.net import Net
from addon.common.addon import Addon

net = Net()

addon_id = 'plugin.video.dij-entertainments-tvshows'
addon = Addon(addon_id, sys.argv)
Addon = xbmcaddon.Addon(addon_id)

sys.path.append(os.path.join(addon.get_path(), 'resources', 'lib'))
data_path = addon.get_profile()

try:
  import StorageServer
except:
  import storageserverdummy as StorageServer
cache = StorageServer.StorageServer(addon_id)


def add_favourite(name,url,img,alt):
    saved_favs = cache.get('favourites_' + alt)
    favs = []

    #print already_fav
    addon.log('ADD FAVS:')
    addon.log('UL: %s'%url)
    addon.log('name: %s'%name)
    addon.log('Thumb %s'%img)
    addon.log('ALT: %s'%alt)
    
    if re.search(r'W\*\[\/COLOR\]\[\/B\]',name,re.I):
        name = re.split(r'\/COLOR\]\[\/B\]\s+',name,re.I)[1]
    if re.match(r'\-\s', name):
        name = re.search(r'\-\s+(.*?)$', name).group(1)

    print name
    favs.append((name,url,img))

    cache.set('favourites_' + alt, str(favs))
               

def add_contextmenu(name, url, thumb, alt, favourite):
    addon.log('ADD CONTEXT: %s'%alt)
    contextMenuItems = []

    if favourite:
        contextMenuItems.append(('Delete from dij-entertainments-tvshows Favourites', 'test'))
    else:
        contextMenuItems.append(('[COLOR red][B]Add[/COLOR][/B] to dij-entertainments-tvshows Favourites','XBMC.RunPlugin(%s)' %
                                 addon.build_plugin_url({'mode': 'add_fav','url': url,'name': name,'img': thumb,'alt': alt})))

    return contextMenuItems
    
    

def specialmessage(url,seen):
    try:
        html = net.http_GET(url).content
    except:
        error()

    items = re.search(r'\<sp\_image\>(.*?)\<\/sp\_image\>.*?\<sp\_background\>?(.*?)\<\/sp\_background\>.*?\<sp\_text\>(.*?)\<\/sp\_text\>',
                      html, re.I|re.DOTALL)
    sp_image = items.group(1)
    sp_back = items.group(2)
    sp_text = items.group(3)

    try:
        image = os.path.join(data_path, 'image.jpg')
        open(image, 'wb').write(net.http_GET(sp_image).content)
    except:
        pass

    if addon.get_setting('seen_special') == 'true':
        gs_seen = addon.get_setting('seen_special_no')
        if seen == gs_seen:
            return
    else:
        pass
    #return
    from pyxbmct.addonwindow import *

      

    #addon.log('IMAGE: %s'%sp_image)
    #addon.log('BACK: %s'%sp_back)
    #addon.log('TEXT: %s'%sp_text)

    print image
        
    window = AddonDialogWindow('dij-entertainments-tvshow\'s [COLOR red][B]SPECIAL[/COLOR][/B] Messages')
    window.setGeometry(850, 600, 40, 40)

    image = Image(os.path.join(data_path, 'image.jpg'))
    window.placeControl(image, 0, 0, rowspan=42, columnspan=41) 

    textBox = TextBox(textColor='')
    window.placeControl(textBox, 26, 1, columnspan=30, rowspan=13)
    textBox.setText('[COLOR black][I]'+sp_text+'[/COLOR][/I]')

    button = Button('[COLOR black]Close[/COLOR]')
    window.placeControl(button, 40, 20, columnspan=5, rowspan=2)
    window.setFocus(button)
    window.connect(button, window.close)
    window.connect(ACTION_NAV_BACK, window.close)
    window.doModal()
    Addon.setSetting('seen_special', value='true')
    Addon.setSetting('seen_special_no', value=seen)
    


def TWITTER(url):
    tweet_text = ''
    net.http_GET('http://twitrss.me/')
    net.get_cookies()
    net.save_cookies(cookie_file)
    net.set_cookies(cookie_file)

    
    html = net.http_GET(url).content

    print html
    
    html = re.sub(r'\&\#x27\;', "'", html, re.I|re.DOTALL)

    for items in re.finditer(r'le\>\<\!\[CDATA\[(.*?)\].*?ate\>(.*?)\s\+', html, re.I|re.DOTALL):
        text = items.group(1)
        date = '[COLOR green][B]'+items.group(2)+'[/COLOR][/B]'

        if re.search(r'pic.tw', text, re.I):
            text = re.split(r'pic.tw', text)[0]

        elif re.match(r'\@\w+\:', text):
            items = re.search(r'(\@\w+\:)(\s\@.*?)$', text, re.I)
            try:
                text = '[COLOR yellow][B]RETWEET: '+items.group(1)+'[/COLOR][/B] '+items.group(2)
            except:
                pass
            #print items.groups()
            #text = re.sub('[COLOR yellow]RETWEET: '+group(1), text)

        
        
        tweet_text = tweet_text+date+'\n'+text+'\n'+'\n'
        #tweet_text = re.sub('
            
    TextBox('test', tweet_text)


def TextBox(heading, tweet_text):

    id = 10147
    xbmc.executebuiltin('ActivateWindow(%d)' % id)
    xbmc.sleep(100)
    win = xbmcgui.Window(id)
    retry = 50
    while (retry > 0):
        try:
            xbmc.sleep(10)
            retry -= 1
            win.getControl(1).setLabel(heading)
            win.getControl(5).setText(str(tweet_text))
            return
        except:
            pass
def SetViewType(viewtype):
    xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_LABEL )
    xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_DATE )
    xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_PROGRAM_COUNT )
    xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_VIDEO_RUNTIME )
    xbmcplugin.setContent(int(sys.argv[1]), 'movies')
    xbmc.executebuiltin("Container.SetViewMode(%s)" % viewtype)
        
